home *** CD-ROM | disk | FTP | other *** search
/ The Arsenal Files 8 / The Arsenal Files Collection #8 (Arsenal Computer) (1996).ISO / prg_casm / snip9611.zip / REDIRECT.C < prev    next >
C/C++ Source or Header  |  1996-11-24  |  2KB  |  96 lines

  1. /* +++Date last modified: 02-Nov-1995 */
  2.  
  3. /*
  4. **  REDIRECT.C - Posix-compliant utilities to handle redirection
  5. **
  6. **  written by Benno Sauer, Vienna, 1991
  7. **  released into public domain
  8. */
  9.  
  10. #include <stdio.h>
  11. #include <fcntl.h>
  12. #include <sys\stat.h>
  13.  
  14. #include "unistd.h"
  15. #include "dirport.h"
  16. #include "snpdosys.h"
  17.  
  18. /*
  19. **  Use these predefined structures for the 3 primary streams.
  20. **  Define others (e.g. stdprn under DOS) as required.
  21. */
  22.  
  23. REDIR_STRUCT redir_stdin, redir_stdout, redir_stderr;
  24.  
  25.  
  26.  
  27. void  start_redirect ( REDIR_STRUCT *s )
  28. {
  29.       if (s->which == fileno(stdin))
  30.             s->what = open ( s->path, O_RDWR, S_IREAD );
  31.       else  s->what = open ( s->path, O_CREAT | O_RDWR, S_IREAD | S_IWRITE );
  32.  
  33.       s->oldhandle = dup ( s->which );
  34.  
  35.       dup2  ( s->what, s->which );
  36.       close ( s->what );
  37.       s->flag = 1;
  38. }
  39.  
  40. void  stop_redirect ( REDIR_STRUCT *s )
  41. {
  42.       if ( s->flag )
  43.       {
  44.             dup2 ( s->oldhandle, s->which );
  45.             close ( s->oldhandle );
  46.             s->flag = 0;
  47.       }
  48. }
  49.  
  50. #ifdef TEST
  51.  
  52. #include <string.h>
  53.  
  54. main()
  55. {
  56.       char line[132];
  57.       int i;
  58.  
  59.       strcpy(redir_stdin.path, "redirect.c");
  60.       redir_stdin.which = fileno(stdin);
  61.  
  62.       strcpy(redir_stdout.path, "x-file");
  63.       redir_stdout.which = fileno(stdout);
  64.  
  65.       strcpy(redir_stderr.path, "file.x");
  66.       redir_stderr.which = fileno(stderr);
  67.  
  68.       start_redirect(&redir_stdin);
  69.       start_redirect(&redir_stdout);
  70.       start_redirect(&redir_stderr);
  71.  
  72.       for (i = 1; !feof(stdin); ++i)
  73.       {
  74.             if (fgets(line, 132, stdin))
  75.             {
  76.                   fputs(line, stdout);
  77.                   fprintf(stderr, "Read line #%d\n", i);
  78.             }
  79.       }
  80.       fflush(stdout);
  81.       fflush(stderr);
  82.  
  83.       stop_redirect(&redir_stdin);
  84.       stop_redirect(&redir_stdout);
  85.       stop_redirect(&redir_stderr);
  86.  
  87.       fputs("All done!\n", stdout);
  88.       fflush(stdout);
  89.       fputs("Hit Enter to exit\n", stderr);
  90.       getchar();
  91.  
  92.       return 0;
  93. }
  94.  
  95. #endif /* TEST */
  96.